// 指定extension.list文件的修改
var extensions = Vue.component('build-extensions', {
    template: readComponentHTML("extensions"),
    props: {
        title: {//卡片标题
            type: String
        },
        path: {//卡片标题
            type: String
        }
    },
    data() {
        return {
            ruleForm: {
                path: ''
            },
            rules: {
                path: [
                    {required: true, message: '请输入扩展包路径', trigger: 'blur'}
                ]
            },
            ftp: {
                baseUrl: ['22.项目扩展包', 'Smartbi_ext'],
                versions: [],
                version: '',
                branches: ['第一个', '第二个'],
                branch: '',
                searchExt: '',
                searchData: [],
                configs: [],
            },
            debug: true, // 开关状态
            debugStatus: "已开启", // 描述
            needOpen: false, // 是否需要开启debug disable状态 不需要则不可以点击
            fileList: [],
            extData: [],
            data: [],
            value: [],
            separator: '', // 不同系统下的文件分割符
            filterMethod(query, item) {
                var querys = $.trim(query).split(/[ ]+/);
                for (var i = 0; i < querys.length; i++) {
                    if (item.label.toLowerCase().indexOf(querys[i].toLowerCase()) > -1) {
                        return true;
                    }
                }
                return false;
            }
        };
    },
    mounted() {
        this.ruleForm.path = this.$store.state.projectPath;
        this.freshData();
        this.separator = this.$root.$data.separator;
    },
    methods: {
        splitShortName(shortName) {
            shortName = this.delsrcweb(shortName);
            if (shortName.indexOf(this.separator)) {
                shortName = shortName.substring(shortName.lastIndexOf(this.separator) + 1);
            }
            return shortName;
        },
        renderFunc(h, option) { // 目前 return 返回的使用了 jsx语法
            var _this = this;
            var shortName = "";
            if (this.data[option.key] && this.data[option.key]["shortName"]) {
                shortName = this.data[option.key]["shortName"];
            } else {
                shortName = this.splitShortName(option.label);
            }
            this.data[option.key]["shortName"] = shortName;
            var html = h("div", {},[h("span", {
                    attrs: {
                        id: option.key,
                    },
                    domProps: {
                        innerHTML: shortName,
                        title: option.label
                    },
                    on: {
                        // 双击实现穿梭框切换
                        click: function () {
                            //简单的逻辑  如果不在 v-model值数组里面，则push，否则从数组中删除
                            if (_this.value.includes(option.key)) {
                                let index = _this.value.indexOf(option.key);
                                _this.value.splice(index, 1);
                            } else {
                                _this.value.push(option.key);
                            }
                        }
                    }
                }),h("i", {
                    class: "el-icon-circle-close",
                    style: {float: "right"},
                    on: {
                        click: function (e) {
                            var historyNames = [];
                            _this.value.forEach((item, index, array) => {
                                historyNames.push(_this.data[item].label);
                            })
                            _this.data.splice(option.key, 1);
                            _this.value = [];
                            historyNames.forEach((item, index, array) => {
                                _this.data.forEach((item2, index, array) => {
                                    if (item === item2.label) {
                                        _this.value.push(index);
                                    }
                                    _this.data[index].key = index;
                                })
                            })
                            e.preventDefault()
                        }
                    }
                }),h("i", {
                    class: "el-icon-document-copy",
                    style: {float: "right"},
                    domProps: {
                        title: "复制路径"
                    },
                    on: {
                        click: function (e) {
                            _this.setCopyText(_this.delsrcweb(option.label), e);
                            e.preventDefault()
                        }
                    }
                }),h("i", {
                    class: "el-icon-document-copy",
                    style: {float: "right"},
                    domProps: {
                        title: "复制名称"
                    },
                    on: {
                        click: function (e) {
                            _this.setCopyText(shortName, e);
                            e.preventDefault()
                        }
                    }
                })]
            );
            return html;
        },
        splitNowAndHistoryPath() {
            var data = [];
            var now = [];
            var history = [];
            this.value.forEach((item, index, array) => {
                history.push(this.data[item].label);
            })
            for (i in this.data) {
                var exist = false;
                this.value.forEach((item, index, array) => {
                    if (i == item) {
                        exist = true;
                        return;
                    }
                })
                if (!exist) {
                    now.push(this.data[i].label);
                }
            }
            data[0] = now;
            data[1] = history;
            return data;
        },
        // 将修改后的扩展包列表更新至文件
        changeList() {
            var that = this;
            that.openLoading();
            var splitData = this.splitNowAndHistoryPath();
            var now = splitData[0];
            var history = splitData[1];

            var postData = new URLSearchParams();
            postData.append("list", now);
            postData.append("history", history);
            postData.append("title", this.$props.title);
            axios.post(
                "/simpledevelop/extension/update",
                postData
            ).then(function (ret) {
                that.closeLoading();
                if (now.length > 0 && that.extData.length > 0) {
                    now.forEach((item, index, array) => {
                        item = that.splitShortName(item) + ".ext";
                        that.extData.forEach((item2, index2, array2) => {
                            if (item === item2.shortName) {
                                that.handleDelete(item2.path);
                            }
                        })
                    })
                }
                that.$message({
                    message: '更新扩展包列表成功',
                    type: 'success'
                })
            })
                .catch(error => this.$message.error(JSON.stringify(error)))
        },
        // 添加新的扩展包到扩展包列表
        addNewPath() {
            this.$refs['ruleFormNewPath'].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.path.indexOf(this.separator + "src" + this.separator + "web") == -1) {
                        this.ruleForm.path += this.separator + "src" + this.separator + "web";
                    }
                    for (let i = 0; i < this.data.length; i++) {
                        if (this.data[i].label === this.ruleForm.path) {
                            for (let j = 0; j < this.value.length; j++) {
                                if (i === this.value[j]) {
                                    this.value.splice(j, 1);
                                    this.$message.success('该扩展包已存在历史记录中,已帮你自动划分过来');
                                    return;
                                }
                            }
                            this.$message.error('该扩展包已存在');
                            return;
                        }
                    }
                    this.data.push({
                        key: this.data.length,
                        label: this.ruleForm.path
                    })
                    this.ruleForm.path = "";
                }
            })
        },
        // 初始化数据
        freshData() {
            // this.$props.title = this.$route.params.title;
            var that = this;
            this.data = [];
            this.value = [];
            axios
                .get('/simpledevelop/extension/showExtensionList?title=' + this.$props.title)
                .then(function (response) {
                    var data = response.data;
                    var firstLen = data[0].length;
                    for (i in data) {
                        if (i == 2) {
                            break;
                        }
                        for (j in data[i]) {
                            j = Number(j);
                            var index = (i == 0) ? j : j + firstLen;
                            that.data.push({
                                key: index,
                                label: data[i][j].path
                            })
                            if (i == 1) {
                                that.value.push(firstLen + j);
                            }
                        }
                    }
                    that.extData = data[2];
                });
        },
        handleDelete(path) {
            var that = this;
            axios
                .get('/simpledevelop/extension/del/extFile?path=' + path + '&title=' + this.$props.title)
                .then(function (response) {
                    that.extData = response.data;
                });
        },
        copyExt(path) {
            var paths = [];
            paths.push(path);
            this.requestCopy(path);
        },
        copyExts() {
            var paths = [];
            this.extData.forEach((item, index, array) => {
                paths.push(item.path);
            })
            this.requestCopy(paths);
        },
        requestCopy(pathArray) {
            var postData = new URLSearchParams();
            postData.append("paths", pathArray);
            axios.post(
                "/simpledevelop/extension/copy/extFile",
                postData
            ).then((res) => this.$message({
                message: '复制成功',
                type: 'success'
            }));
        },
        handleSuccess(response, file, fileList) {
            this.$message({
                message: '上传成功',
                type: 'success'
            });
            this.extData = response;
            this.$refs.upload.clearFiles();
        },
        changeTab(tabPage) {
            if (tabPage.loaded) {
                return;
            }
            var that = this;
            // 切换到debug
            if (tabPage.index === "2") {
                axios
                    .get('/simpledevelop/extension/isDebug?title=' + this.$props.title)
                    .then(function (response) {
                        var data = response.data;
                        if (!data.data) {
                            that.$message({
                                message: data.desc,
                                type: 'warning'
                            });
                            that.debug = false;
                            that.debugStatus = "未开启";
                            that.needOpen = true;
                        }
                    });

            } else if (tabPage.index === "3") {
                var that = this;
                axios.post(
                    "/simpledevelop/ftp/init"
                ).then(function (ret) {
                    that.ftp.baseUrl = ret.data[0]
                    that.ftp.versions = ret.data[1];
                    that.ftp.version = that.ftp.versions[0];
                    that.ftp.branches = ret.data[2];
                    that.ftp.branch = that.ftp.branches[0];
                })
                    .catch(error => this.$message.error(JSON.stringify(error)))
            }
        },
        changeDebug(status) {
            if (!status) {
                this.debug = true;
            } else {
                var that = this;
                axios
                    .get('/simpledevelop/extension/openDebug?title=' + this.$props.title)
                    .then(function (response) {
                        var data = response.data;
                        if (data.data) {
                            that.$message({
                                message: data.desc,
                                type: 'success'
                            });
                            that.debug = true;
                            that.debugStatus = "已开启";
                            that.needOpen = false;
                        }
                    });
            }
        },
        searchRefExt() {
            var that = this;
            that.openLoading();
            var now = this.splitNowAndHistoryPath()[0];
            for (i in now) {
                now[i] = this.splitShortName(now[i]);
            }
            var postData = new URLSearchParams();
            postData.append("baseUrls", this.ftp.baseUrl);
            postData.append("version", this.ftp.version);
            postData.append("branch", this.ftp.branch);
            postData.append("searchExt", this.ftp.searchExt);
            postData.append("extensionsExt", now);
            postData.append("configs", this.ftp.configs);
            axios.post(
                "/simpledevelop/ftp/search",
                postData
            ).then(function (ret) {
                that.closeLoading();
                that.ftp.searchData = [];
                if (ret.data) {
                    var count = 0;
                    for (i in ret.data) {
                        that.ftp.searchData.push(ret.data[i])
                        count++;
                    }
                    that.$message({
                        message: 'FTP查询完成，找到相关扩展包：' + count + '个',
                        type: 'success'
                    })
                }
            })
                .catch(error => this.$message.error(JSON.stringify(error)))
        },
        importExt(index) {
            var ext = this.ftp.searchData[index];
            var finallyPath = ext.ftpPath + "/" + ext.select + "/";
            var that = this;
            that.openLoading();
            var postData = new URLSearchParams();
            postData.append("ftpPath", finallyPath);
            postData.append("localPath", this.path);
            postData.append("fileName", ext.name);
            axios.post(
                "/simpledevelop/ftp/download",
                postData
            ).then(function (ret) {
                that.closeLoading();
                if (ret.data.reasonCode == 0) {
                    that.$message({
                        message: ret.data.desc,
                        type: 'success'
                    })
                    var postData = new URLSearchParams();
                    postData.append("path", that.path);
                    postData.append("title", that.$props.title);
                    axios.post(
                        "/simpledevelop/extension/ext/fresh",
                        postData
                    ).then(function (ret) {
                        that.extData = ret.data;
                    })

                    for (i in that.data) {
                        if (that.data[i].shortName === ext.name) {
                            for (j in that.value) {
                                if (that.value[j] == parseInt(i)) {
                                    return;
                                }
                            }
                            that.value.push(parseInt(i));
                            that.changeList();
                        }
                    }
                } else if (ret.data.reasonCode == 3) {
                    const h = that.$createElement;
                    var elems = [];
                    elems.push(h('span', null, ret.data.desc));
                    elems.push(h('span', { style: 'color: red' }, '发现其他ext扩展包，点击其余扩展包可进行更换'));
                    ret.data.data.forEach((item, index, array) => {
                        elems.push(h('span', null, [h('el-button', {
                                attrs:{type : "primary", size : "small"},
                                on: {
                                    click: function (e) {
                                        that.ftp.searchData[index].name = item;
                                        that.importExt(index);
                                        e.preventDefault()
                                    }
                                }
                        }, item + ".ext")]))
                    })
                    that.$message({
                        message: h('div', null, [elems]),
                        type: 'warning'
                    });
                } else {
                    that.$message({
                        message: ret.data.desc,
                        type: 'error'
                    })
                }
            })
                .catch(error => this.$message.error(JSON.stringify(error)))
        }
    },
    watch: {
        // 如果路由有变化，会再次执行该方法
        "$route": "freshData",
        listenExtPath: function (newValue, oldValue) {
            this.ruleForm.path = newValue;
        }
    },
    computed: {
        listenExtPath() {
            return this.$store.state.projectPath;
        }
    }
})